package com.secsbrain.cmdb.biz.utils.command;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 自定义输出处理
 * Created by yangyang.zhang on 2017/9/11.
 */
public class CustomStreamHandler extends AutoFlushingPumpStreamHandler {
    private final ExecuteStrategy executeStrategy;

    public CustomStreamHandler(final ExecuteStrategy executeStrategy,
                               final InputStream input) {
        super(input);
        this.executeStrategy = executeStrategy;
    }

    @Override
    public void setProcessOutputStream(final InputStream is) {
        super.outputThread = createCallbackProcessor(is);
    }

    @Override
    public void setProcessErrorStream(final InputStream is) {
        super.errorThread = createCallbackProcessor(is);
    }

    private Thread createCallbackProcessor(InputStream inputStream) {
        return new Thread(() -> {
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    executeStrategy.processLine(line);
                }
            } catch (IOException e) {
                executeStrategy.handleException(e);
            }
        });
    }
}
